#include "t_thread.h"
#include <iostream>

#ifdef __linux__
#include <pthread.h>
#elif _WIN32
#include <windows.h>
#endif

namespace T_THREAD
{
    Thread::Thread()
        : state_(State::Ready),
          stop_requested_(false)
    {}

    Thread::~Thread()
    {
        // 确保线程在对象销毁前被正确停止和join
        if (state_ == State::Running) {
            request_stop();
        }
        join();
    }

    // 移动构造函数
    Thread::Thread(Thread&& other) noexcept
        : thread_(std::move(other.thread_)),
          state_(other.state_.load()),
          stop_requested_(other.stop_requested_.load())
    {
        other.state_ = State::Stopped;
    }

    // 移动赋值运算符
    Thread& Thread::operator=(Thread&& other) noexcept
    {
        if (this != &other) {
            // 先join当前线程（如果存在）
            if (state_ == State::Running) {
                request_stop();
                join();
            }
            thread_ = std::move(other.thread_);
            state_ = other.state_.load();
            stop_requested_ = other.stop_requested_.load();
            other.state_ = State::Stopped;
        }
        return *this;
    }

    bool Thread::start(const std::string& name, std::function<void()> function)
    {
        if (state_ != State::Ready) {
            return false; // 只能启动一次
        }
        state_ = State::Running;
        stop_requested_ = false;
        thread_ = std::make_unique<std::thread>(&Thread::thread_entry, this, name, std::move(function));
        return true;
    }

    void Thread::thread_entry(const std::string& name, std::function<void()>& function)
    {
        if (!name.empty()) {
            set_current_thread_name(name);
        }

        try {
            if (function) {
                function();
            }
        }
        catch (const std::exception& e) {
            std::cerr << "Exception caught in thread " << std::this_thread::get_id() << ": " << e.what() << std::endl;
        }
        catch (...) {
            std::cerr << "Unknown exception caught in thread " << std::this_thread::get_id() << std::endl;
        }

        state_ = State::Stopped;
    }

    void Thread::set_current_thread_name(const std::string& name)
    {
        #ifdef __linux__
        // linux下线程名最长16字节（包含'\0'）
        pthread_setname_np(pthread_self(), name.substr(0, 15).c_str());
        #elif _WIN32
        // 需要 Windows 10 version 1607 或更高版本
        std::wstring wname(name.begin(), name.end());
        SetThreadDescription(GetCurrentThread(), wname.c_str());
        #endif
    }

    void Thread::request_stop()
    {
        stop_requested_ = true;
    }

    void Thread::join()
    {
        if (thread_ && thread_->joinable()) {
            thread_->join();
        }
        thread_.reset();
        state_ = State::Stopped; // 确保join后状态为Stopped
    }

    Thread::State Thread::get_state() const
    {
        return state_;
    }

    bool Thread::is_stop_requested() const
    {
        return stop_requested_;
    }

    std::thread::id Thread::get_id() const
    {
        return thread_ ? thread_->get_id() : std::thread::id();
    }

    std::mutex& Thread::get_mutex()
    {
        return mutex_;
    }
    std::condition_variable& Thread::get_cv()
    {
        return cv_;
    }

} // namespace MY_THREAD